# 基本函数定义


def greet(name):
    """这是一个简单的问候函数"""
    return f"你好，{name}！"

# 调用函数
message = greet("小王")
print(message)

# 带默认参数的函数
def greet_with_title(name, title="先生"):
    return f"你好，{title} {name}！"

print(greet_with_title("小王"))
print(greet_with_title("小王", "女士"))

# 关键字参数
print(greet_with_title(title="女士", name="李梅"))

# *args - 接收任意数量的位置参数

def sum_all(*args):
    """计算所有参数和"""
    total = 0
    for num in args:
        total += num
    return total
print(sum_all(1, 2, 3, 4, 5))

# **kwargs - 接收任意数量的关键字参数
def print_info(**kwargs):
    """打印所有参数"""
    for key, value in kwargs.items():
        print(f"{key}: {value}")

print_info(name="小王", age=18, city="上海")

# 匿名函数 lambda
square = lambda x: x **2
print(square(5))

# 在高阶函数中使用
numbers = [1,2,3,4,5]
square_numbers = list(map(lambda x: x**2, numbers))
print(square_numbers)

# 排序中使用
students = [("小王", 18), ("小李", 17), ("小张", 19)]
# 按年龄排序
students_sorted = sorted(students,key= lambda x : x[1])
print(students_sorted)